/**
 * 隐患上报 列表页
 *
 * 作者 wanghw
 * 日期 2024-08-20 09:23:04
 */
layui.use(['jquery', 'laydate', 'febs', 'form', 'table', 'commonJS', 'validate'], function () {
    var $ = layui.jquery,
        laydate = layui.laydate,
        febs = layui.febs,
        form = layui.form,
        table = layui.table,
        commonJS = layui.commonJS,
        validate = layui.validate,
        $view = $('#febs-hazardReportPlan'),
        $query = $view.find('#query'),
        $searchForm = $view.find('#hazardReportPlan-table-form'),
        $hazardOperation = $view.find('#hazardOperation'),
        tableIns;

    form.verify(validate);
    form.render();

    initDate();
    initSelect();
    initTable();

    function initDate() {
        //初始化日期控件
        laydate.render({
            elem: '#laydate-range',
            range: ['#start-date', '#end-date'],
            format: 'yyyy-MM-dd',
            btns:['now','confirm']
        })
        $('#end-date').val(commonJS.getCurrentDateStr(new Date()));
        $('#start-date').val(commonJS.getPastDateStr(new Date(),7));
        form.render();

    }
    function initSelect() {
        initProject();
    }



    function initTable() {
        tableIns = febs.table.init({
            elem: $view.find('table'),
            id: 'hazardReportPlanTable',
            url: ctx + 'hazardReportPlan/list',
            where: getQueryParams(),
            height: getTableHeight(),
            skin: '',
            cols: [[
                {type: 'numbers',title: '序号'},
                {field: 'reportNo', title: '报告编号', width: 180, event: 'detail',templet:function (d) {
                        return '<p style="color:#01aaed;cursor:pointer">'+d.reportNo+'</p>'
                    }},
                {field: 'tenantName', title: '公司名称', minWidth: 120,hide:!hasHeadCompanyRole},
                {field: 'projectName', title: '项目名称', minWidth: 120},
                {field: 'areaName', title: '位置区域', minWidth: 120},
                {field: 'filePath', title: '隐患图片', width: 120 , align: 'center', templet: function (d) {
                        if(d.fileList){
                            var img = '<img class="tupian" style="width: 60px;height: 60px;" src="' + ctx + d.fileList[0].smallPath + '" ' +
                                'data-bigsrc="' + ctx + d.fileList[0].filePath + '" lay-event="imgEvent" /></img>';
                            return img;
                        }

                    }},
                {field: 'createdTime', title: '上报时间', width: 160,align:'center'},
                {field: 'status', title: '状态', width: 150 ,align:'center',templet:'#planStatusTransfer'},
                {title: '操作', toolbar: '#hazardReportPlan-tool',align:'center', width: 265,fixed:'right'}
            ]],
        });
    }

    table.on('sort(hazardReportPlanTable)', function (obj) {
        tableIns.reload({
            initSort: obj,
            where: $.extend(getQueryParams(), {
                field: obj.field,
                order: obj.type
            }),
            autoSort: true
        });
    });

    function reloadPage(curr) {
        var _curr = $view.find(".layui-laypage-em").next().html();
        if (!!curr) {
            _curr = curr;
        }
        tableIns.reload({where: getQueryParams(), page: {curr: _curr}});
    }

    $query.on('click', function () {
        reloadPage(1);
    });


    table.on('tool(hazardReportPlanTable)', function (obj) {
        var data = obj.data,
            layEvent = obj.event;
        if (layEvent === 'del') {
            febs.modal.confirm('删除隐患信息', '确定删除所选数据？', function () {
                deleteIds(data.reportId);
            });
        }
        if (layEvent === 'reply') {
            febs.modal.open('留言', 'hazardReportPlan/message/' + data.reportId, {
                area: $(window).width() <= 750 ? '95%':['75%', '90%'],
                data: {

                },
            });
        }
        if (layEvent === 'imgEvent') {
            $view.find(".big-img-div img").attr("src", ctx + obj.data.fileList[0].filePath);
        }

        if (layEvent === 'plan') {
            febs.modal.open('制定计划', 'hazardReportPlan/plan/' + data.reportId, {
                area: $(window).width() <= 750 ? '95%':['80%', '90%'],
                btn: ['提交', '取消'],
                yes: function (index, layero) {
                    $('#hazardReportPlan-edit').find('#submit').trigger('click');
                },
                btn2: function () {
                    layer.closeAll();
                },
                data: {

                },
            });
        }
        if (layEvent === 'detail') {
            febs.modal.open('隐患信息信息详情', 'hazardList/detail/' + data.reportId, {
                area: $(window).width() <= 750 ? '90%' : ['80%', '90%'],
                shadeClose: true,
                btn: ['取消'],
                yes: function (index, layero) {
                    layer.close(index)
                },
            });
        }
    });

    $view.find(".big-img-div img").load(function () {
        commonJS.showImgBig($view, this, this.width, this.height);
    });

    $view.find(".big-img-div").click(function () {//再次点击淡出消失弹出层
        $(this).fadeOut("fast");
    });



    function getQueryParams() {

        return {
            tenantId: getTenantId(),
            areaId:  $searchForm.find("select[name='areaId']").find("option:selected").val(),
            projectId: $searchForm.find("select[name='projectId']").find("option:selected").val(),
            hazardOperation: $searchForm.find("select[name='hazardOperation']").find("option:selected").val(),

            startDate: $searchForm.find('input[name="startDate"]').val(),
            endDate: $searchForm.find('input[name="endDate"]').val(),
            invalidate_ie_cache: new Date()
        };
    }

    function deleteIds(ids) {
        febs.get(ctx + 'hazardReport/delete/' + ids, null, function () {
            febs.alert.success('删除数据成功');
            $query.trigger('click');
        })
    }

    function getTenantId(){
        return $searchForm.find('select[name="tenantId"]').find("option:selected").val();
    }

    form.on('select(tenantId)', function(obj){
        // 获取选中项 value
        initProject();
        $("#queryAreaId").empty();
        form.render();
    });

    function initProject() {
        //初始化项目
        var data ={
            tenantId:getTenantId()
        };
        $("#queryProjectId").empty();
        //初始化商品单位
        febs.getSync(ctx + 'baseProject', data, function (r) {
            // console.log("项目列表" + JSON.stringify(r.data))
            var areaLis = r.data;
            var options = '<option value="">请选择</option>';
            $.each(areaLis, function (index, item) {
                options += '<option value="' + item.projectId + '">' + item.projectName + '</option>'
            })
            $("#queryProjectId").append(options);
        });
        form.render();
    }

    form.on('select(projectId)', function(obj){
        // 获取选中项 value
        var projectId = obj.value;
        if(projectId == ''){
            $("#queryAreaId").empty();
        }else {
            initProjectAreaId()
        }
        form.render();
    });
    function initProjectAreaId() {
        //初始化项目区域
        var data ={
            tenantId:getTenantId(),
            projectId:$searchForm.find('select[name="projectId"]').find("option:selected").val()
        };
        $("#queryAreaId").empty();
        febs.getSync(ctx + 'baseProjectArea', data, function (r) {
            // console.log("区域列表" + JSON.stringify(r.data))
            var areaLis = r.data;
            var options = '<option value="">请选择</option>';
            $.each(areaLis, function (index, item) {
                options += '<option value="' + item.areaId + '">' + item.areaName + '</option>'
            })
            $("#queryAreaId").append(options);
        });
    }

    function submitIds(ids) {
        febs.get(ctx + 'hazardReportPlan/submit/' + ids, null, function () {
            febs.alert.success('提交成功');
            $query.trigger('click');
        })
    }

    function getTableHeight() {
        return commonJS.calcTableHeight();
    }

    $(window).resize(function () {
        tableIns.reload({height: getTableHeight()});
    });

});